package com.qianchang.microfinance.view.hsbindbank;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.ToastUtil;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.UnBindDataBean;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.widgets.WebLayout;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;

import org.json.JSONException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * 版 权: 广西鸿胜科技有限公司
 * 描 述: 银行卡解绑
 * 修 改 人: chen G L
 * 修改时间: 2018/1/10 16:33
 */

public class HSUnBindBankCardActivity extends BaseActivity{

//    @BindView(R.id.webView_id)
//    WebView webView;
//    @BindView(R.id.progressBarLoading)
//    ProgressBar mLoadingProgress;


    private LinearLayout mLinearLayout;
    protected AgentWeb mAgentWeb;
    private boolean isConfirmlGoing = false;

    public boolean isConfirmlGoing() {
        return isConfirmlGoing;
    }

    public void setConfirmlGoing(boolean confirmlGoing) {
        isConfirmlGoing = confirmlGoing;
    }




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unbindbankcard_layout);
//        ButterKnife.bind(this);
        initView();

        unBindBankCard();

    }

    @Override
    protected void initView() {
        super.initView();
        setTitleName("解绑银行卡");
        mLinearLayout = (LinearLayout) findViewById(R.id.container);

        mAgentWeb = AgentWeb.with(this)//
                .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))//
                .useDefaultIndicator()//
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setWebLayout(new WebLayout(this))
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                .interceptUnkownScheme() //拦截找不到相关页面的Scheme
                .createAgentWeb()//
                .ready()
                .go(url);

        if(mAgentWeb!=null){
            //注入对象
            mAgentWeb.getJsInterfaceHolder().addJavaObject("android",new UnBindBankAndroidInterface(mAgentWeb,HSUnBindBankCardActivity.this));
        }


    }

    private void unBindBankCard(){
        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();

        HttpParams params = new HttpParams();
        params.put("userId", usid);
        show();

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.UNBIND_BANKCARD, params, new RequestCallBack<UnBindDataBean>() {


            @Override
            public void onSuccess(JsonResult<UnBindDataBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    UnBindDataBean openAccBean = response.getObject();
                    if(openAccBean != null){
                        try {
                            pars = getParameter(openAccBean);
                            initWebView();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }else{
                        ToastUtil.getInstant().show(HSUnBindBankCardActivity.this, response.getDescription());
                    }
                } else {
                    ToastUtil.getInstant().show(HSUnBindBankCardActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(HSUnBindBankCardActivity.this, msg);
                dismiss();
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private String getParameter(UnBindDataBean unBindDataBean) throws JSONException, UnsupportedEncodingException {

        Map<String,String> map = new HashMap<String,String>();
        url = unBindDataBean.getAction();
        String sign = unBindDataBean.getSign();
        String platformNo = unBindDataBean.getPlatformNo();
        String userDevice = unBindDataBean.getUserDevice();
        String keySerial = unBindDataBean.getKeySerial();
        String reqData = unBindDataBean.getReqData();
        String serviceName = unBindDataBean.getServiceName();

        map.put("sign",sign);
        map.put("platformNo",platformNo);
        map.put("userDevice",userDevice);
        map.put("keySerial",keySerial);
        map.put("reqData",reqData);
        map.put("serviceName",serviceName);
        String parameter = "";
        String subParameter = "";

        Iterator entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            parameter = parameter + key + "=" + URLEncoder.encode(value,"utf-8") + "&";
        }
        subParameter = parameter.substring(0, parameter.length() - 1);
        return subParameter;
    }



    private String url;
    private String pars = "";
    private Map<String,String> mMap;

    private void initWebView(){

        mAgentWeb.getLoader().postUrl(url,pars.getBytes());

    }

    private String getMapStr(UnBindDataBean unBindDataBean) throws UnsupportedEncodingException {
        Map<String,String> map = new HashMap<String,String>();
        url = unBindDataBean.getAction();
        String sign = unBindDataBean.getSign();
        String platformNo = unBindDataBean.getPlatformNo();
        String userDevice = unBindDataBean.getUserDevice();
        String keySerial = unBindDataBean.getKeySerial();
        String reqData = unBindDataBean.getReqData();
        String serviceName = unBindDataBean.getServiceName();

        map.put("sign",sign);
        map.put("platformNo",platformNo);
        map.put("userDevice",userDevice);
        map.put("keySerial",keySerial);
        map.put("reqData",reqData);
        map.put("serviceName",serviceName);

        String parameter = "";
        String subParameter = "";
        Iterator entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            parameter = parameter + key + "=" + URLEncoder.encode(value,"utf-8") + "&";
        }
        subParameter = parameter.substring(0, parameter.length() - 1);
        return subParameter;
    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            setTitle(title);
        }
    };

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.i("Info", "BaseWebActivity onPageStarted");
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mAgentWeb.destroy();
        mAgentWeb.getWebLifeCycle().onDestroy();
    }

}
